package com.zhuchaooasystem.ui.home;

import android.content.Intent;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.trace.LBSTraceClient;
import com.baidu.trace.LocationMode;
import com.baidu.trace.OnTrackListener;
import com.baidu.trace.Trace;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.zhuchaooasystem.R;
import com.zhuchaooasystem.adapter.MyFragmentPageAdapter;
import com.zhuchaooasystem.base.BaseActivity;
import com.zhuchaooasystem.base.BaseEvent;
import com.zhuchaooasystem.common.Key;
import com.zhuchaooasystem.entity.UserInfo;
import com.zhuchaooasystem.event.OAToServiceEvent;
import com.zhuchaooasystem.presenter.home.HomeContract;
import com.zhuchaooasystem.presenter.home.HomePresenter;
import com.zhuchaooasystem.ui.home.fragment.MessageFragment;
import com.zhuchaooasystem.ui.home.fragment.MineFragment;
import com.zhuchaooasystem.ui.home.fragment.OAFragment;
import com.zhuchaooasystem.ui.home.fragment.ServiceFragment;
import com.zhuchaooasystem.ui.home.fragment.message.MessageReadActivity;
import com.zhuchaooasystem.ui.setting.SettingActivity;
import com.zhuchaooasystem.utils.AppUtils;
import com.zhuchaooasystem.utils.ToastUtil;
import com.zhuchaooasystem.widget.ViewpagerNoScroll;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class HomeActivity extends BaseActivity<HomePresenter> implements HomeContract.View {

    @BindView(R.id.actionbar_txt_title)
    TextView txt_title;
    @BindView(R.id.act_home_vp_menu)
    ViewpagerNoScroll vp_menu;
    @BindView(R.id.act_home_rg_menu)
    RadioGroup rg_menu;
    @BindView(R.id.actionbar_iv_right_mine)
    ImageView actionbarIvRight;
    @BindView(R.id.actionbar_iv_right_message)
    ImageView actionbarIvRightMessage;
    //----
    private List<Fragment> fragmentList;
    private ServiceFragment serviceFragment;
    private OAFragment oaFragment;
    private MessageFragment messageFragment;
    private MineFragment mineFragment;
    private MyFragmentPageAdapter adapter;
    //----
    private long lastClickTime = 0;
    //----百度鹰眼相关
    private LBSTraceClient client;
    private final long serviceId = 133044;
    private Trace trace;
    //----
    private boolean isFromPush;
    private String username;

    @Override
    protected int getLayout() {
        return R.layout.activity_home;
    }

    @Override
    protected HomePresenter getPresenter() {
        return new HomePresenter(mContext, this);
    }

    @Override
    protected void initVariables() {
        if (null != getIntent()) {
            isFromPush = getIntent().getBooleanExtra("isFromPush", false);
        }
        username = UserInfo.getInstance().getUserName();
        fragmentList = new ArrayList<>();
        //----
        serviceFragment = new ServiceFragment();
        oaFragment = new OAFragment();
        messageFragment = new MessageFragment();
        mineFragment = new MineFragment();
        //----
        fragmentList.add(serviceFragment);
        fragmentList.add(oaFragment);
        fragmentList.add(messageFragment);
        fragmentList.add(mineFragment);
        //初始化百度鹰眼服务
        initBaiDuTrace();
        //----
        RxBus.get().register(this);
        //----
        initJpush();
        //----
        mPresenter.checkVersion();
    }

    private void initJpush() {
        if (JPushInterface.isPushStopped(getApplicationContext())) {
            JPushInterface.resumePush(getApplicationContext());
        }
        JPushInterface.setAlias(getApplicationContext(), username, new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {
                //绑定成功
                if (i != 0) {
                    ToastUtil.showShort(HomeActivity.this, "推送绑定失败");
                }
            }
        });
    }

    /**
     * 初始化百度鹰眼服务
     */
    private void initBaiDuTrace() {
        //实例化轨迹服务客户端
        client = new LBSTraceClient(getApplicationContext());
        //实例化轨迹服务
        trace = new Trace(getApplicationContext(), serviceId, UserInfo.getInstance().getUserName(), 2);
        // 设置定位模式
        client.setLocationMode(LocationMode.High_Accuracy);
        //设置位置采集和打包周期
        client.setInterval(300, 300);
        client.setOnTrackListener(new OnTrackListener() {
            @Override
            public void onRequestFailedCallback(String s) {
            }

            @Override
            public Map onTrackAttrCallback() {
                return super.onTrackAttrCallback();
            }

            @Override
            public void onQueryHistoryTrackCallback(String s) {
                super.onQueryHistoryTrackCallback(s);
            }
        });
        //开启轨迹服务
        client.startTrace(trace);
    }


    @Override
    protected void initView() {
        initViewpager();
        initRadioGroup();
        //默认选中第一页
        if (isFromPush) {
            pagerChanged(2);
            txt_title.setText(getString(R.string.actionbar_title_message));
        } else {
            vp_menu.setCurrentItem(0);
            txt_title.setText(getString(R.string.actionbar_title_service));
        }

    }

    private void initViewpager() {
        adapter = new MyFragmentPageAdapter(getSupportFragmentManager(), fragmentList);
        vp_menu.setAdapter(adapter);

    }

    private void initRadioGroup() {
        rg_menu.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                final int index = radioGroup.indexOfChild(radioGroup.findViewById(radioGroup.getCheckedRadioButtonId()));
                pagerChanged(index);
            }
        });
    }


    /**
     * 切换当前页面
     *
     * @param position
     */
    private void pagerChanged(int position) {
        vp_menu.setCurrentItem(position);
        titleChanged(position);
        //----
        RadioButton rb;
        for (int i = 0; i < rg_menu.getChildCount(); i++) {
            rb = (RadioButton) rg_menu.getChildAt(i);
            if (i == position) {
                rb.setChecked(true);
                rb.setTextColor(getResources().getColor(R.color.color_1bc3ad));
                rb.setBackgroundColor(getResources().getColor(R.color.color_ffffff));
            } else {
                rb.setChecked(false);
                rb.setTextColor(getResources().getColor(R.color.color_ffffff));
                rb.setBackgroundColor(getResources().getColor(R.color.color_1bc3ad));
            }
        }
    }

    private void titleChanged(int position) {
        switch (position) {
            case 0:
                txt_title.setText(getString(R.string.actionbar_title_service));
                actionbarIvRight.setVisibility(View.GONE);
                actionbarIvRightMessage.setVisibility(View.GONE);
                break;
            case 1:
                txt_title.setText(getString(R.string.actionbar_title_OA));
                actionbarIvRight.setVisibility(View.GONE);
                actionbarIvRightMessage.setVisibility(View.GONE);
                break;
            case 2:
                txt_title.setText(getString(R.string.actionbar_title_message));
                actionbarIvRight.setVisibility(View.GONE);
                actionbarIvRightMessage.setVisibility(View.VISIBLE);
                break;
            case 3:
                txt_title.setText(getString(R.string.actionbar_title_mine));
                actionbarIvRightMessage.setVisibility(View.GONE);
                actionbarIvRight.setVisibility(View.VISIBLE);
                actionbarIvRight.setImageResource(R.drawable.ic_mine_set);
                break;
        }
    }

    @Override
    protected void initDataAndLoadData() {

    }

    public TextView getTxt_title() {
        return txt_title;
    }

    public void setTxt_title(TextView txt_title) {
        this.txt_title = txt_title;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(this);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (SystemClock.uptimeMillis() - lastClickTime > Key.EXIT_GAP) {
            Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
            lastClickTime = SystemClock.uptimeMillis();
            return false;
        } else {
            HomeActivity.this.finish();
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 我的界面  右上角跳转到设置
     *
     * @param view
     */
    @OnClick({R.id.actionbar_iv_right_mine, R.id.actionbar_iv_right_message})
    public void onClick(View view) {
        switch (view.getId()) {
            //我的
            case R.id.actionbar_iv_right_mine:
                Intent intent = new Intent(HomeActivity.this, SettingActivity.class);
                startActivity(intent);
                break;
            //信息
            case R.id.actionbar_iv_right_message:
                AppUtils.jump(HomeActivity.this, MessageReadActivity.class);
                break;
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag("logout")})
    public void logout(BaseEvent baseEvent) {
        finish();
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag("RedactToService")})
    public void RedactToService(BaseEvent event) {
        if (null != serviceFragment) {
            serviceFragment.RedactToService();
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag("turnToService")})
    public void turnToService(BaseEvent<OAToServiceEvent> baseEvent) {
        if (null != baseEvent && null != baseEvent.event && null != serviceFragment) {
            OAToServiceEvent event=baseEvent.event;
            pagerChanged(0);
            txt_title.setText(event.getItemName());
            actionbarIvRight.setVisibility(View.GONE);
            actionbarIvRightMessage.setVisibility(View.GONE);
            serviceFragment.changeState(event.getItemValue());
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag("refreshTitle")})
    public void refreshTitle(BaseEvent<String> baseEvent) {
        if (null != baseEvent && null != baseEvent.event) {
            txt_title.setText(baseEvent.event);
            actionbarIvRight.setVisibility(View.GONE);
            actionbarIvRightMessage.setVisibility(View.GONE);
        }
    }

}
